# -*- coding:utf-8 -*-
from models import *
from django.shortcuts import render_to_response
from django.template import RequestContext 
from django.core.context_processors import csrf
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib import auth
import datetime
import random
from django.db.models import Q
    
def index(request):
    section = Section.objects.all()
    category = Category.objects.all()
    cat_mix = list(category)
    random.shuffle(cat_mix)
    product = Product.objects.filter(id_cat=cat_mix[0].id)
    catalog = {}
    for sec in section:
        temp=[]
        for cat in category:
            if cat.id_sec.id == sec.id:
                temp.append(cat)
        if temp:
            catalog.update({sec.name: temp})
    context = {
               'catalog': catalog,
               'pr_rand': product,
               'title': u'Комплектующие',
               'user': request.user,
              }
    context.update(csrf(request))
    templates_path = 'example.html'
    return render_to_response(templates_path,context)

def get_sec(request, id):
    category = Category.objects.filter(id_sec=id)
    product = Product.objects.all()
    catalog = {}
    for cat in category:
        temp=[]
        for pr in product:
            if pr.id_cat.id == cat.id:
                temp.append(pr)
        if temp:
            catalog.update({cat.name: temp})
    cat_mix = list(category)
    random.shuffle(cat_mix)
    try:
        pr = Product.objects.filter(id_cat=cat_mix[0].id)
        templates_path = 'example.html'
        context = {'catalog_sec': catalog,
                   'pr_rand': pr,
                   'title': u'Комплектующие - %s' % (category[0].id_sec.name),
                   'user': request.user,
                   }
        context.update(csrf(request))
        return render_to_response(templates_path, context)
    except:
        raise Http404

def get_cat(request, id):
    category = Category.objects.filter(id=id)
    cat_mix = list(category)
    random.shuffle(cat_mix)
    pr = Product.objects.filter(id_cat=cat_mix[0].id)
    
    product = Product.objects.filter(id_cat=id)
    templates_path = 'example.html'
    context = {'product': product,
               'pr_rand': pr,
               'title': u'Комплектующие - %s - %s' % (category[0].id_sec.name, category[0].name),
               'user': request.user,
               }
    context.update(csrf(request))
    return render_to_response(templates_path, context)

def get_pr(request, id):
    product = Product.objects.filter(id=id)
    if product.count() != 0:
        cat_mix = list(Category.objects.filter(id=product[0].id_cat.id))
        random.shuffle(cat_mix)
        pr = Product.objects.filter(id_cat=cat_mix[0].id)
        product = product[0]
        templates_path = 'example.html'
        context = {'the_product': product,
                   'pr_rand': pr,
                   'title': u'Комплектующие - %s - %s - %s' % (product.id_cat.id_sec.name, product.id_cat.name, product.name),
                   'user': request.user,
                   }
        context.update(csrf(request))
        return render_to_response(templates_path, context)
    else:
        raise Http404

def ajax_cat(request, id):
    category = Category.objects.filter(id_sec=id)
    templates_path = 'update.html'
    context = {'category': category}
    context.update(csrf(request))
    return render_to_response(templates_path, context)

def search(request):
    template = 'search_result.html'
    context = RequestContext(request)
    context.update(csrf(request))
    
    if not request.method=='POST':
        context.update({'title': u'Результат поиска',
                        'error': u'По вашему запросу ничего не найдено.'})
        return render_to_response(template, context)
    query = request.POST['query']
    search_result = {}
    search_result.update({u'Разделы': Section.objects.filter(Q(name__contains=query) | Q(description__contains=query)),
                          u'Категории': Category.objects.filter(Q(name__contains=query) | Q(description__contains=query)),
                          u'Товары': Product.objects.filter(Q(name__contains=query) | Q(description__contains=query)),
                          })
    if not search_result[u'Разделы'] and not search_result[u'Категории'] and not search_result[u'Товары']:
        context.update({'title': u'Результат поиска',
                        'error': u'По вашему запросу ничего не найдено.'})
        return render_to_response(template, context)
    context.update({'title': u'Результат поиска',
                    'search_result': search_result,
                    })
    return render_to_response(template, context)